package com.example.springbootdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncConfig {

    /**
     * 自定义线程池配置。因为配置了多个线程池，所以Spring中能找到唯一的实现TaskExecutor接口不成立。并且没有Bean名字叫taskExecutor的Bean
     */
    @Bean("myTaskExecutor")  // bean名称很重要！
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);                    // 核心线程数
        executor.setMaxPoolSize(10);                    // 最大线程数
        executor.setQueueCapacity(100);                 // 队列容量
        executor.setThreadNamePrefix("myTaskExecutor-Async-");  // 线程名前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
        executor.setWaitForTasksToCompleteOnShutdown(true); // 等待任务完成再关闭
        executor.setAwaitTerminationSeconds(60);        // 等待时间
        executor.initialize();
        return executor;
    }

//    /**
//     * 也可以配置多个线程池，使用时通过名称指定
//     */
//    @Bean("ioTaskExecutor")
//    public Executor iOTaskExecutor() {
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(10);
//        executor.setThreadNamePrefix("IO-Async-");
//        executor.initialize();
//        return executor;
//    }
}